import 'package:chat_client/screens/home_screen.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:chat_client/utils/image_picker_helper.dart'; // 引入封装的图片选择工具类
import 'package:chat_client/utils/validation.dart'; // 验证工具类
import 'package:chat_client/widgets/global_widgets.dart'; // 自定义组件
import 'package:chat_client/services/auth_service.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({super.key});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final AuthService _authService = AuthService.instance;

  final TextEditingController _nicknameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  XFile? _selectedImage; // 文件对象
  bool _isLoading = false; // 加载状态

  /// 选择图片（支持裁剪）
  Future<void> _pickImage() async {
    try {
      final file = await ImagePickerHelper.pickAndProcessImage();
      if (file == null) throw Exception('图片丢失，请稍后重试');

      setState(() {
        _selectedImage = file;
      });
    } catch (e) {
      _showError(title: '图片处理失败', message: e.toString());
    }
  }

  /// 获取当前头像路径（安全访问）
  String? get _avatarPath {
    return _selectedImage?.path;
  }

  @override
  void dispose() {
    ImagePickerHelper.releaseImage(_selectedImage); // 组件销毁时释放Web资源
    super.dispose();
  }

  /// 处理注册逻辑
  Future<void> _register() async {
    final nickname = _nicknameController.text.trim();
    final phoneNumber = _phoneController.text.trim();
    final password = _passwordController.text.trim();

    setState(() {
      _isLoading = true;
    });

    // 校验昵称
    String? nicknameError = Validator.validateNikeName(nickname);
    if (nicknameError != null) {
      _showError(message: nicknameError);
      setState(() => _isLoading = false);
      return;
    }

    // 校验手机号
    String? phoneNumberError = Validator.validatePhoneNumber(phoneNumber);
    if (phoneNumberError != null) {
      _showError(message: phoneNumberError);
      setState(() => _isLoading = false);
      return;
    }

    // 校验密码
    String? passwordError = Validator.validatePassword(password);
    if (passwordError != null) {
      _showError(message: passwordError);
      setState(() => _isLoading = false);
      return;
    }

    try {
      bool isRegistered = await _authService.register(
          nickName: nickname,
          password: password,
          phoneNumber: phoneNumber,
          imageFile: _selectedImage);
      if (isRegistered) {
        // 注册成功
        WidgetsBinding.instance.addPostFrameCallback((_) {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const HomeScreen()),
          );
        });
        ImagePickerHelper.releaseImage(_selectedImage);
      } else {
        _showError(message: '注册失败，请稍后重试');
      }
    } catch (e) {
      _showError(message: e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 显示错误提示弹窗
  void _showError({String title = '注册失败', required String message}) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CustomErrorDialog(
          title: title,
          message: message,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕宽度
    double width = MediaQuery.of(context).size.width;

    // 在 Web 平台时，设置宽度为 600（根据需求调整宽度），在手机和平板上使用默认宽度
    double formWidth = width > 500 ? 500 : width * 0.8;

    return Scaffold(
      appBar: AppBar(title: const Text('手机号注册'), elevation: 0),
      body: Center(
        child: Container(
          width: formWidth,
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 头像选择区域
                GestureDetector(
                  onTap: _pickImage,
                  child: CustomSquareAvatar(
                    imageUrl: _avatarPath,
                    size: 100,
                    backgroundColor: const Color.fromARGB(255, 205, 202, 202),
                  ),
                ),

                const SizedBox(height: 10),
                Text('点击上传头像',
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.grey[600], fontSize: 14)),
                const SizedBox(height: 30),

                CustomTextField(
                    label: '用户昵称',
                    controller: _nicknameController,
                    hintText: '例如：陈晨'),
                const SizedBox(height: 10),
                CustomTextField(
                    label: '手机号 +86',
                    controller: _phoneController,
                    hintText: '请输入11位手机号'),
                const SizedBox(height: 10),
                CustomTextField(
                    label: '密码',
                    controller: _passwordController,
                    hintText: '请输入6-20位密码',
                    isPassword: true),
                const SizedBox(height: 20),

                _isLoading
                    ? const CircularProgressIndicator()
                    : SizedBox(
                        width: formWidth, // 按照相同的宽度限制按钮宽度
                        child: ElevatedButton(
                          onPressed: _register,
                          child: const Text('注册'),
                        ),
                      ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
